package org.fuys.etp.core;

import lombok.Data;
import org.apache.commons.lang3.reflect.FieldUtils;
import org.fuys.etp.core.model.event.EtpPersistentConfigChangeEvent;
import org.fuys.etp.core.model.res.EtpGlobalUpdateRes;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.ApplicationEventPublisher;
import org.springframework.stereotype.Component;

import java.lang.reflect.Field;
import java.util.HashMap;
import java.util.Map;

/**
 * @projectName: fuys-etp-final
 * @package: org.fuys.etp.core
 * @className: EtpPersistentConfig
 * @author: WangJing
 * @description: TODO
 * @date: 2025/2/18 16:08
 * @version: 1.0
 */
@Component
@Data
@ConfigurationProperties(prefix = "etp.persistent",ignoreInvalidFields = true)
public class EtpPersistentConfig {

    private String history;

    private String poolCoreSize;

    private String poolMaxSize;

    private String poolKeepAliveTime;

    private String poolAliveTimeUnit;

    private ApplicationEventPublisher eventPublisher;

    private EtpGlobalConfigUpdater updater;

    EtpPersistentConfig(ApplicationEventPublisher eventPublisher){
        this.eventPublisher = eventPublisher;
        updater = new EtpGlobalConfigUpdater();
    }

    public EtpGlobalUpdateRes updateByUpdater(String fieldName, Object value){
        return updater.update(fieldName,value);
    }

    public class EtpGlobalConfigUpdater{

        public  EtpGlobalUpdateRes update(String fieldName, Object value){
            final Field field = FieldUtils.getField(EtpPersistentConfig.class, fieldName, true);
            if(field == null){
                throw new IllegalArgumentException("Fuys etp全局配置中并不存在这样的配置:"+fieldName);
            }
            try {
                FieldUtils.writeField(field, EtpPersistentConfig.this,value,true);
                EtpPersistentConfigChangeEvent event = new EtpPersistentConfigChangeEvent(this,EtpPersistentConfig.this);
                EtpPersistentConfig.this.eventPublisher.publishEvent(event);
                return EtpGlobalUpdateRes.builder().result(true).build();
            } catch (IllegalAccessException e) {
                e.printStackTrace();
                return EtpGlobalUpdateRes.builder().result(false).build();
            }
        }

    }

    public Map<String,Object> toMap(){
        Map<String,Object> map = new HashMap<>();
        map.put("persistentHistory",history);
        map.put("persistentCoreSize",poolCoreSize);
        map.put("persistentMaxSize",poolMaxSize);
        map.put("persistentKeepAliveTime",poolKeepAliveTime);
        map.put("persistentAliveTimeUnit",poolAliveTimeUnit);
        return map;
    }
}
